<template>
  <el-card>
    <h2>上传头像</h2>
    <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :headers="uploadHeaders"
    :before-upload="beforeUpload"
    :on-change="handleChange"
    :on-success="handleSuccess"
    :on-error="handleError"
    >
    <el-button size="small" type="primary">上传头像</el-button>
    </el-upload>
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
  </el-card>
</template>

<script>
// import axios from 'axios';

export default {
  data() {
    return {
      imageUrl: '',
      uploadHeaders: {
        Authorization: `Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbkBleGFtcGxlLmNvbSIsImlhdCI6MTcyOTE3NjUyNiwiZXhwIjoxNzI5MTgwMTI2fQ.X4lvaySDOIa9jEGl403b-FvgEkYhADU0L6GhCgJrkaoVf4uekG_GtOswlQ7ufj0wFf9AAVAM57BRcW5MzwyY5Q` // 替换为你的 JWT
      },
      uploadUrl: 'http://localhost:8082/api/v1/upload'  // 后端上传接口 URL
    };
  },
  methods: {
    beforeUpload(file) {
      // 文件上传前的检查，限制文件类型
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$message.error('上传头像只能是图片!');
      }
      return isImage;
    },
    handleChange(file) {
      // 处理上传状态改变时的逻辑
      if (file.status === 'success') {
        // 上传成功后，直接处理
        this.handleSuccess(file.response, file);
      } else if (file.status === 'error') {
        this.handleError(new Error('Upload failed'), file);
      }
    },
    handleSuccess(response, file) {
      // 处理上传成功的逻辑
      console.log('Upload success:', file);
      this.imageUrl = response.url; // 假设后端返回了头像 URL
      this.$message.success('头像上传成功！');
    },
    handleError(err, file) {
      console.log('Upload error:', file);
      this.$message.error('头像上传失败，请重试！');
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  margin-top: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-top: 10px; /* 增加间距 */
}
</style>
